package edu.upf.da.p2p.sm.client.manager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.upf.da.p2p.sm.P2PMessage;
import edu.upf.da.p2p.sm.P2PMessageListener;
import edu.upf.da.p2p.sm.P2PUserClient;
import edu.upf.da.p2p.sm.client.message.AuthRequest;
import edu.upf.da.p2p.sm.client.message.AuthResponse;

public class AuthManager extends P2PMessageListener {

	private static final Log log = LogFactory.getLog(AuthManager.class);

	private P2PUserClient p2pc;
	private AuthResponse loginresponse;
	private AuthResponse logoutresponse;

	public AuthManager(P2PUserClient client){
		p2pc = client;
	}

	public boolean login(String user, String pass) throws InterruptedException {
		//TODO Enviar request, y esperar response.
		AuthRequest ar = new AuthRequest(user,pass);
		ar.setTo(p2pc.getServiceManager().getServiceAddress("auth"));
		loginresponse = null;
		p2pc.sendMessage(ar);
		while(loginresponse == null){
			Thread.sleep(100);
		}
		return loginresponse.isOK();
	}
	public boolean logout() throws InterruptedException{
		AuthRequest ar = new AuthRequest();
		ar.setTo(p2pc.getServiceManager().getServiceAddress("auth"));
		logoutresponse = null;
		p2pc.sendMessage(ar);
		while(logoutresponse == null){
			Thread.sleep(100);
		}
		return loginresponse.isOK();
	}

	public int getLoginError(){
		return loginresponse.getErrorCode();
	}

	public int getLogoutError(){
		return logoutresponse.getErrorCode();
	}

	public void processMessage(P2PMessage pkt) {
		AuthResponse ar = (AuthResponse)pkt;
		if(ar.isLogIn()){
			loginresponse = ar;
		}else if(ar.isLogOut()){
			logoutresponse = ar;
		}
	}

}
